//
//  AppDelegate.m
//  Traveling
//
//  Created by 郑文青 on 16/6/29.
//  Copyright © 2016年 zhengwenqing’s mac. All rights reserved.
//

#import "AppDelegate.h"
#import "AppDelegate+Location.h"
#import "AppDelegate+ConfigUI.h"
#import "UIDevice+TSHSystemInfo.h"
#import "DataManager.h"
#import "LauchViewController.h"

#import "JPUSHService.h"

#import <UserNotifications/UserNotifications.h>

@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    [JPUSHService setupWithOption:launchOptions appKey:@"9dfebf60cb9f6a3c3e9f10aa"
                          channel:@"appStore"
                 apsForProduction:true
            advertisingIdentifier:nil];
    [self registerRemoteNotification];
    // jpush
    [self setJPushConfig];
    
    self.window = [[UIWindow alloc]initWithFrame:CGRectMake(0, 0, kScreenW, kScreenH)];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    

    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    LauchViewController *launchVC =  [[LauchViewController alloc] initWithNibName:@"LauchViewController" bundle:nil];
    self.window.rootViewController = launchVC;

    [self setConfigUI];

    return YES;
}

- (void)registerRemoteNotification
{
    UIApplication *application = [UIApplication sharedApplication];
    
    application.applicationIconBadgeNumber = 0;
    
    NSLog(@"%@", [UIDevice SystemVersion]);
    
    if ([[UIDevice SystemVersion] floatValue] < 10.0f) {
        //iOS 10 以下
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound categories:nil];
        [application registerUserNotificationSettings:settings];
    }
    else {
        //iOS 10以上(包含iOS10)
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        ///设置代理(AppDelegate 里面实现它的代理方法)
        center.delegate = (id)application.delegate;
        [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert) completionHandler:^(BOOL granted, NSError *_Nullable error) {
            if (!error) {
                NSLog(@"request authorization succeeded!");
            }
        }];
        [center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings *_Nonnull settings) {
            NSLog(@"%@", settings);
        }];
    }
    [[UIApplication sharedApplication] registerForRemoteNotifications];
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


/// 注册成功后返回设备信息
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    if (deviceToken != nil) {
        NSLog(@"%@", [NSString stringWithFormat:@"Device Token: %@", deviceToken]);

        ///极光推送设备token处理
        [JPUSHService registerDeviceToken:deviceToken];
    }
}

/// 远程通知注册失败委托
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
    NSLog(@"%@", [error description]);

}

/**
 *  在iOS7中，通过推送通知，可以启动一个后台下载操作任务。
 *  该方法在IOS6下是不能被调用的,如想适配IOS6 要调用类似的另外一个方法
 *
 *  @param application       application
 *  @param userInfo          userInfo 推送内容
 *  @param completionHandler 后台操作
 */
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
      completionHandler(UIBackgroundFetchResultNewData);
}

/// 在没有启动本App时，收到服务器推送消息，下拉消息会有快捷回复的按钮，点击按钮后调用的方法，根据identifier来判断点击的哪个按钮
- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forRemoteNotification:(NSDictionary *)userInfo completionHandler:(void (^)())completionHandler
{
    NSLog(@"completionHandler");
}

- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler
{
    completionHandler(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert);
}

- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler
{
   
}

#pragma mark - 本地推送

/// 收到本地推送消息后调用的方法
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
    ///目前没有使用到极光推送的本地通知
    ///此通知会影响在线客服本地通知,在线客服接受本地通知后,不需要弹框
    //[JPUSHService showLocalNotificationAtFront:notification identifierKey:nil];
    NSLog(@"%@", notification);
}

/// 本地推送通知 IOS8之后有的方法
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
{
    // 成功注册registerUserNotificationSettings:后，回调的方法
    NSLog(@"%@", notificationSettings);
}

/// 在非本App界面时收到本地消息，下拉消息会有快捷回复的按钮，点击按钮后调用的方法，根据identifier来判断点击的哪个按钮，notification为消息内容
- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forLocalNotification:(UILocalNotification *)notification completionHandler:(void (^)())completionHandler
{
    NSLog(@"%@----%@", identifier, notification);
    completionHandler(); // 处理完消息，最后一定要调用这个代码块
}


@end
